package com.dzqc.fly.controller.mobile;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.dzqc.fly.common.*;
import com.dzqc.fly.db.form.*;
import com.dzqc.fly.db.pojo.AppFilePojo;
import com.dzqc.fly.exception.flyException;
import com.dzqc.fly.service.LeaveService;
import com.dzqc.fly.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/leave")
@Tag(name = "LeaveController", description = "学生请假相关")
@Slf4j
@EnableAutoConfiguration
public class LeaveController {

    @Value("${file.upload.dir}")
    private String uploadFilePath;

    @Autowired
    private UserService userService;

    @Autowired
    private LeaveService leaveService;

    //@GetMapping("/getUserInfo")
    @RequestMapping(value="/getUserInfo" ,method = RequestMethod.GET)
    @SaCheckLogin
    @Operation(summary = "获取学生相关信息")
    public Result getUserInfo(){
        int userId= StpUtil.getLoginIdAsInt();
        HashMap hashMap =userService.searchUserInfo(userId);
        hashMap.put("fdy",hashMap.get("fdy").toString());
        return Result.ok().put("result",hashMap);
    }


   // @PostMapping("/insert")
    @RequestMapping(value="/insert" ,method = RequestMethod.POST)
    @Operation(summary = "添加请假记录")
    @SaCheckLogin
    @Transactional(rollbackFor = flyException.class)
    public Result insert(@RequestPart(value = "files",required = false) MultipartFile files[],@Valid  @RequestPart("form") InsertLeaveForm form){
        //验证结束时间是不是早于开始时间
        DateTime date_1 = DateUtil.parse(form.getStart());
        DateTime date_2 = DateUtil.parse(form.getEnd());
        if(date_1.isAfterOrEquals(date_2)){
            return Result.error("请假开始时间不能晚于或者等于截止时间");
        }
        String leave_id=UUID.randomUUID().toString().replaceAll("-","");
        String shenpi_id=UUID.randomUUID().toString().replaceAll("-","");
        HashMap userinfoMap =userService.searchUserInfo(StpUtil.getLoginIdAsInt());
        HashMap leaveparam=new HashMap(){{

            put("leave_id", leave_id);//请假单id
            put("shenpi_id",shenpi_id);//审批单id
            put("sno", userinfoMap.get("sno"));//学号
            put("fdyid",userinfoMap.get("fdyid"));
            put("fdy",userinfoMap.get("fdy"));
            put("name", userinfoMap.get("name"));//姓名
            put("creat_time",DateTime.now());//请假单创建时间
            put("begintime", form.getStart());//请假开始时间
            put("endtime", form.getEnd());//请假结束时间
            put("reason",form.getReason());//请假原因
            put("description",form.getDescription());//外出路线描述
            put("hours",date_1.between(date_2, DateUnit.HOUR));
        }};
        long hours=date_1.between(date_2, DateUnit.HOUR);
        if(hours>72){
            leaveparam.put("sjid",userinfoMap.get("sjid"));
            leaveparam.put("sj",userinfoMap.get("sj"));
        }
        if (files!=null) {//有附件传附件，没有附件跳过此逻辑
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getOriginalFilename();
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                String fileNewName= (UUID.randomUUID().toString().replaceAll("-",""))+suffixName;
                String size= StringUtil.convertToString(files[i].getSize()/1024)+"kb";
                File fileDir = new File(uploadFilePath);
                if (!fileDir.getParentFile().exists()) {
                    fileDir.getParentFile().mkdirs();
                }
                try {
                    File newFile = new File(fileDir.getAbsolutePath() + File.separator + fileNewName);
                    files[i].transferTo(newFile);
                    AppFilePojo app=new AppFilePojo();
                    app.setLeave_id(leave_id);
                    app.setOriginalname(fileName);
                    app.setTargetname(fileNewName);
                    app.setIp(IpUtils.getHostIp());
                    app.setPath(fileDir.getAbsolutePath() + File.separator + fileName);
                    app.setSize(size);
                    app.setCreattime( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    leaveService.insertfiles(app);
                } catch (Exception e) {
                    log.error("发生错误: {}", e);
                    Result result=Result.error();
                    return  result;

                }
            }
        }

        //TODO向tb_leave和tb_leave_shenpi表插入数据
        int rows = leaveService.insertleave(leaveparam);
        int shenpirows=leaveService.insertleaveshenpi(leaveparam);
        return Result.ok().put("rows",rows);
    }

    @RequestMapping(value="/insertnew" ,method = RequestMethod.POST)
    @SaCheckLogin
    @Operation(summary = "学生端添加请假记录（表单数据）")
    public Result insertnew(@Valid @RequestBody InsertLeaveForm form){
        //验证结束时间是不是早于开始时间
        DateTime date_1 = DateUtil.parse(form.getStart());
        DateTime date_2 = DateUtil.parse(form.getEnd());
        if(date_1.isAfterOrEquals(date_2)){
            return Result.error("请假开始时间不能晚于或者等于截止时间");
        }
        String leave_id=UUID.randomUUID().toString().replaceAll("-","");
        String shenpi_id=UUID.randomUUID().toString().replaceAll("-","");
        HashMap userinfoMap =userService.searchUserInfo(StpUtil.getLoginIdAsInt());
        HashMap leaveparam=new HashMap(){{

            put("leave_id", leave_id);//请假单id
            put("shenpi_id",shenpi_id);//审批单id
            put("sno", userinfoMap.get("sno"));//学号
            put("fdyid",userinfoMap.get("fdyid"));
            put("fdy",userinfoMap.get("fdy"));
            put("name", userinfoMap.get("name"));//姓名
            put("creat_time", DateTime.now());//请假单创建时间
            put("begintime", form.getStart());//请假开始时间
            put("endtime", form.getEnd());//请假结束时间
            put("reason",form.getReason());//请假原因
            put("description",form.getDescription());//外出路线描述
            put("imgpath",form.getImgpath());//请假上传的图片
            put("hours",date_1.between(date_2, DateUnit.HOUR));
        }};
        long hours=date_1.between(date_2, DateUnit.HOUR);
        if(hours>72){
            leaveparam.put("sjid",userinfoMap.get("sjid"));
            leaveparam.put("sj",userinfoMap.get("sj"));
        }

        //TODO向tb_leave和tb_leave_shenpi表插入数据
        int rows = leaveService.insertleave(leaveparam);
        int shenpirows=leaveService.insertleaveshenpi(leaveparam);
        return Result.ok().put("rows",rows).put("leave_id",leave_id);
    }
    @RequestMapping(value="/insert2022" ,method = RequestMethod.POST)
    @SaCheckLogin
    @Operation(summary = "学生端添加请假记录（insert2022）")
    public Result insert2022(@RequestBody TestFileForm TestFieForm){
        List Filelist = TestFieForm.getFiles();
        System.out.println(TestFieForm.getFiles());
        return Result.ok().put("json",TestFieForm.getFiles()) ;
    }
    /**
     * 多个文件上传
     * @param files
     * @return
     * @throws JSONException
     */
   // @ResponseBody
    @RequestMapping(value="/uploadFiles" ,method = RequestMethod.POST)
    //@PostMapping("/uploadFiles")
    @Operation(summary = "手机端学生请假多文件上传接口")
    public Result fileUploads(@RequestParam("files") MultipartFile files[]) throws JSONException {

        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String fileNewName= (UUID.randomUUID().toString().replaceAll("-",""))+suffixName;
            String size= StringUtil.convertToString(files[i].getSize()/1024)+"kb";
            File fileDir = new File(uploadFilePath);
            if (!fileDir.getParentFile().exists()) {
                fileDir.getParentFile().mkdirs();
            }
            try {
                File newFile = new File(fileDir.getAbsolutePath() + File.separator + fileNewName);
                files[i].transferTo(newFile);
                AppFilePojo app=new AppFilePojo();
                app.setLeave_id("12121");
                app.setOriginalname(fileName);
                app.setTargetname(fileNewName);
                app.setIp(IpUtils.getHostIp());
                app.setPath(fileDir.getAbsolutePath() + File.separator + fileName);
                app.setSize(size);
                app.setCreattime( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                leaveService.insertfiles(app);
            } catch (Exception e) {
                log.error("发生错误: {}", e);
                Result result=Result.error();
                return  result;

            }
        }
        Result result=Result.ok().put("message","文件上传成功!");
        return result;
    }

    @RequestMapping(value="/searchLeaveList" ,method = RequestMethod.POST)
   // @PostMapping("/searchLeaveList")
    @SaCheckLogin
    @Operation(summary = "查询学生请假记录（未完成）")
    public Result searchLeaveList(@Valid @RequestBody searchLeaveListForm form){
        int page=form.getPage();
        int length=form.getLength();
        int start=(page-1)*length;
        HashMap param= JSONUtil.parse(form).toBean(HashMap.class);
        param.put("start",start);
        param.put("userId",StpUtil.getLoginIdAsInt());
        PageUtils pageUtils=leaveService.searchLeaveList(param);
        return Result.ok().put("page",pageUtils).put("datacount", pageUtils.getList().size());
    }

    @PostMapping("/searchLeaveDetail")
    @Operation(summary = "查询学生请假记录详情")
    public Result searchLeaveDetail(@Valid @RequestBody searchLeaveDetailForm form){
        HashMap param= JSONUtil.parse(form).toBean(HashMap.class);
        HashMap resultMap = leaveService.searchLeaveDetail(param);
        LinkedList<HashMap> hashMaps = leaveService.searchLeaveDetailFiles(param);
        if (hashMaps != null&&hashMaps.size()>0) {
            resultMap.put("list",hashMaps);
        }
       else if (hashMaps == null||hashMaps.size()==0) {
            resultMap.put("list"," ");
        }
        return Result.ok().put("result",resultMap);
    }

    @PostMapping("/searchLeaveListDone")
    @SaCheckLogin
    @Operation(summary = "查询学生请假记录（已完成）")
    public Result searchLeaveListDone(@Valid @RequestBody searchLeaveListForm form){
        int page=form.getPage();
        int length=form.getLength();
        int start=(page-1)*length;
        HashMap param= JSONUtil.parse(form).toBean(HashMap.class);
        param.put("start",start);
        param.put("userId",StpUtil.getLoginIdAsInt());
        PageUtils pageUtils=leaveService.searchLeaveListDone(param);
        return Result.ok().put("page",pageUtils);
    }

    @GetMapping("/searchMonth")
    @SaCheckLogin
    @Operation(summary = "查询学生请假月份(统计)")
    public Result searchMonth(){
        LinkedList<HashMap> resultMap = leaveService.searchMonth(StpUtil.getLoginIdAsInt());
        return Result.ok().put("result",resultMap);
    }

    @PostMapping("/searchNumOfStudentLeave")
    @SaCheckLogin
    @Operation(summary = "统计学生请假情况(统计)")
    public Result searchNumOfStudentLeave(@Valid @RequestBody searchNumOfStudentLeaveForm form){
        HashMap param= JSONUtil.parse(form).toBean(HashMap.class);
        HashMap userinfoMap =userService.searchUserInfo(StpUtil.getLoginIdAsInt());
        param.put("sno",userinfoMap.get("sno"));
        LinkedList<HashMap> resultMap = leaveService.searchNumOfStudentLeave(param);
        return Result.ok().put("result",resultMap);
    }


     @PostMapping("/updateUnfinishedLeaveStatus")
     @SaCheckLogin
     @Operation(summary = "撤销未处理的请假单接口")
     public Result updateUnfinishedLeaveStatus(@Valid @RequestBody updateUnfinishedLeaveStatusForm form){
         HashMap param= JSONUtil.parse(form).toBean(HashMap.class);
         int rows=leaveService.updateUnfinishedLeaveStatus(param);
         return Result.ok().put("rows",rows);
     }

    //点击撤销数据回显接口
    @PostMapping("/searchLeaveDetail2FinishedLeave")
    @SaCheckLogin
    @Operation(summary = "点击撤销,销假数据回显接口(已处理)")
    public Result searchLeaveDetail2FinishedLeave(@Valid @RequestBody searchLeaveDetailForm form){
        HashMap param= JSONUtil.parse(form).toBean(HashMap.class);
        HashMap resultMap = leaveService.searchLeaveDetail2FinishedLeave(param);
        return Result.ok().put("result",resultMap);
    }

    //确认撤销接口，需要填写撤销原因
   // @PostMapping("/updateFinishedLeave")
    @RequestMapping(value="/updateFinishedLeave" ,method = RequestMethod.POST)
    @SaCheckLogin
    @Operation(summary = "撤销已处理的请假单接口")
    public Result updateFinishedLeave(@Valid @RequestBody updateFinishedLeaveForm form){
        HashMap param= JSONUtil.parse(form).toBean(HashMap.class);
        int rows=leaveService.updateFinishedLeave(param);
        return Result.ok().put("rows",rows);
    }


    /**
     *
     * @param form：传递的参数address需要是真实的当前地址如：广东省深圳市南山区深圳大学杜鹃山(白石路北250米)
     * @return
     */
   // @PostMapping("/updateLapseLeave")
    @RequestMapping(value="/updateLapseLeave" ,method = RequestMethod.POST)
    @SaCheckLogin
    @Operation(summary = "销假（超时销假）接口")
    public Result updateLapseLeave(@Valid @RequestBody(required = false) updateLapseLeaveForm form){
        HashMap param= JSONUtil.parse(form).toBean(HashMap.class);
        HashMap resultMap = leaveService.searchLeaveDetail2FinishedLeave(param);

        DateTime date_now = DateUtil.parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        DateTime date_end = DateUtil.parse(resultMap.get("endtime").toString());//请假截止时间


        if(date_now.isAfterOrEquals(date_end)){
            if (param.get("overrevokes")==null||param.get("overrevokes")=="") {
                return Result.error("请填写超时销假原因！");
            }
            //超时销假状态不一样
            param.put("status",4);
            int rows=leaveService.updateLapseLeave(param);
            return Result.ok().put("rows",rows);

        }
        param.put("status",3);
        int rows=leaveService.updateLapseLeave(param);
        return Result.ok().put("rows",rows);
    }


}
